package com.zq.widget.inverted.game.role;

import android.content.Context;
import android.graphics.RectF;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangqiang on 2018/3/29.
 */
public final class RoleRoot extends RoleGroup {

    private List<Role> childRoles = new ArrayList<>();

    public RoleRoot(Context context) {
        super(context);
    }

    /**
     * 计算碰撞
     */
    public void computeCollision() {

        int count = childRoles.size();
        for (int i = 0; i < count; i++) {

            Role src = childRoles.get(i);
            for (int j = i + 1; j < count; j++) {

                Role target = childRoles.get(j);

                if (isCollision(src,target)) {

                    src.onCollisionWith(target);
                    target.onCollisionWith(src);
                }
            }
        }
    }


    @Override
    public void notifyRoleTreeChange() {
        super.notifyRoleTreeChange();
        childRoles.clear();
        getAllRoles(this,childRoles);

//        Log.i("Test","================" + childRoles.size());
    }

    private static void getAllRoles(Role role, List<Role> roles) {

        if(!(role instanceof RoleRoot)){
            roles.add(role);
        }

        if (role instanceof RoleGroup) {

            RoleGroup roleGroup = (RoleGroup) role;
            final int childCount = roleGroup.getChildCount();
            for (int i = 0; i < childCount; i++) {

                Role child = roleGroup.getChildAt(i);
                getAllRoles(child, roles);
            }
        }
    }

    private static boolean isCollision(Role src,Role target){

        return RectF.intersects(src.collisionBounds(),target.collisionBounds());
    }
}
